package com.xci.wx.mp.controller;

import com.xci.core.helper.JsonHelper;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

@Slf4j
@Controller
@RequestMapping("/wx/redirect")
public class WxRedirectController {
    @Resource
    private WxMpService wxService;

    @GetMapping(value = "/greet")
    @ResponseBody
    public Object greetUser(@RequestParam String code, ModelMap map) {
        // if (!this.wxService.switchover(appid)) {
        //     throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
        // }

        try {
            WxMpOAuth2AccessToken accessToken = wxService.oauth2getAccessToken(code);
            WxMpUser user = wxService.oauth2getUserInfo(accessToken, null);
            return JsonHelper.serialize(user);
        } catch(WxErrorException e) {
            e.printStackTrace();
        }
        return "失败";
    }

    @GetMapping(value = "/build", produces = "text/plain;charset=utf-8")
    @ResponseBody
    public String build() {
        // http://www.icoc.group/get-weixin-code.html?appid=wx9ba192f96c7f8bb0&scope=snsapi_userinfo&state=&redirect_uri=http%3A%2F%2Fwx.piaoa.com.cn%2Fwx%2Fredirect%2Fgreet

        // http://www.xa96716.com/

        var url = "http://www.xa96716.com/wx/redirect/greet";
        return wxService.oauth2buildAuthorizationUrl(url, WxConsts.OAuth2Scope.SNSAPI_BASE, null)
                +"<br>"+wxService.oauth2buildAuthorizationUrl(url, WxConsts.OAuth2Scope.SNSAPI_USERINFO, null);
    }
}
